﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models.WeChat.Dtos.QYDepartment;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 企业号用户
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-08-13 
    /// </summary>
    [Route("api/WeChat/QYUser")]
    public class QYUserController : BaseApiController
    {
        private QYUserBll qYUserBll = new QYUserBll();
        private QYDepartmentBll qYDepartmentBll = new QYDepartmentBll();
        private UserBll userBll = new UserBll();

        #region GET
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList(KeywordInput input)
        {
            var data = await qYUserBll.GetList();
            if (input.keyword.IsNotEmptyOrNull())
            {
                data = data.FindAll(x => x.Account.Contains(input.keyword) || x.RealName.Contains(input.keyword) || x.MobilePhone.Contains(input.keyword));
            }
            var output = data.MapToList<QYUserListOutput>();
            return Success(new { list = output });
        }
        #endregion

        #region POST
        /// <summary>
        /// 同步用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("Actions/Synchronization")]
        [AllowAnonymous]
        public async Task<ResponseResult> Synchronization()
        {
            try
            {
                var department = await qYDepartmentBll.GetSyncList();
                if (department.Count == 0)
                {
                    return Error("请先同步部门！");
                }
                else
                {
                    var users = await userBll.GetList();
                    await qYUserBll.Synchronization(users);
                    return Success("同步成功");
                }
            }
            catch (Exception)
            {
                return Error("操作过于频繁");
            }
        }
        #endregion
    }
}